<?php

namespace App\Dao;

use App\Model\CategoryModel;

class CategoryDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = CategoryModel::query();

        $query->when(checkIsHasField($params,'category_id'),function ($query)use ($params){
            $query->where('category_id',$params['category_id']);
        });

        $query->when(checkIsHasField($params,'is_show_index'),function ($query)use ($params){
            $query->where('is_show_index',$params['is_show_index']);
        });

        $query->when(checkIsHasField($params,'show'),function ($query)use ($params){
            $query->where('show',$params['show']);
        });

        $query->when(checkIsHasField($params,'shop_id'),function ($query)use ($params){
            $query->where('shop_id',$params['shop_id']);
        });

        return $query->orderByDesc('created_at');
    }

    public static function categorys($params = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        return self::builder_query($params)->paginate();
    }

    public static function add(array $params)
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        if(self::builder_query()->create($params) === false){
            self::error('添加失败!');
        }
    }

    public static function categorysWithNotPage($params = []): array
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        return self::builder_query($params)->get()->toArray();
    }

    public static function edit(array $params)
    {
        if(!checkIsHasField($params,'shop_id')){
            $params['shop_id'] = getShopId();
        }
        if(self::builder_query(['category_id'=>self::deleteParamId($params,'category_id')])->update(self::filterFields($params,new CategoryModel())) === false){
            self::error('修改失败');
        }
    }

    public static function category_info(array $array)
    {
        if(!checkIsHasField($array,'shop_id')){
            $array['shop_id'] = getShopId();
        }
        return self::builder_query($array)->first()->toArray();
    }

    public static function delete(array $params)
    {
        if(self::builder_query(['category_id'=>self::deleteParamId($params)])->delete() === false){
            self::error('删除失败!');
        }
    }
}
